package serviceswarm

import (
	"context"
	"encoding/json"
	"github.com/aberic/gnomon"
	"github.com/docker/docker/api/types"
	"github.com/pkg/errors"
	"google.golang.org/grpc"
	"gykjgit.dccnet.com.cn/chain/proto/swarm"
)

// ImageList ImageList
func ImageList(url string) ([]types.ImageSummary, error) {
	var images []types.ImageSummary
	resp, err := gnomon.GRPCRequestPools(url, func(conn *grpc.ClientConn) (i interface{}, err error) {
		// 创建grpc客户端
		cli := swarm.NewImageServerClient(conn)
		//客户端向grpc服务端发起请求
		return cli.List(context.Background(), &swarm.ReqImageList{})
	})
	if nil == err {
		if response, ok := resp.(*swarm.RespImageList); ok {
			if err = json.Unmarshal(response.Images, &images); nil == err {
				return images, nil
			}
			return nil, errors.Wrap(err, "image list failed")
		}
		return nil, errors.New("image list failed, can not tarns interface to response")
	}
	return nil, errors.Wrap(err, "image list failed")
}

// ImagePull ImagePull
func ImagePull(url, refStr string) (*swarm.RespImagePull, error) {
	resp, err := gnomon.GRPCRequestPools(url, func(conn *grpc.ClientConn) (i interface{}, err error) {
		// 创建grpc客户端
		cli := swarm.NewImageServerClient(conn)
		//客户端向grpc服务端发起请求
		return cli.Pull(context.Background(), &swarm.ReqImagePull{RefStr: refStr})
	})
	if nil == err {
		if response, ok := resp.(*swarm.RespImagePull); ok {
			return response, nil
		}
		return nil, errors.New("image pull failed, can not tarns interface to response")
	}
	return nil, errors.Wrap(err, "image pull failed")
}

// ImageRemove ImageRemove
func ImageRemove(url, imageID string) ([]types.ImageDeleteResponseItem, error) {
	var imageItems []types.ImageDeleteResponseItem
	resp, err := gnomon.GRPCRequestPools(url, func(conn *grpc.ClientConn) (i interface{}, err error) {
		// 创建grpc客户端
		cli := swarm.NewImageServerClient(conn)
		//客户端向grpc服务端发起请求
		return cli.Remove(context.Background(), &swarm.ReqImageRemove{ID: imageID})
	})
	if nil == err {
		if response, ok := resp.(*swarm.RespImageRemove); ok {
			if err = json.Unmarshal(response.ImageItems, &imageItems); nil == err {
				return imageItems, nil
			}
			return nil, errors.Wrap(err, "image remove failed")
		}
		return nil, errors.New("image remove failed, can not tarns interface to response")
	}
	return nil, errors.Wrap(err, "image remove failed")
}

// ImageTag ImageTag
func ImageTag(url, source, target string) (*swarm.RespImageTag, error) {
	resp, err := gnomon.GRPCRequestPools(url, func(conn *grpc.ClientConn) (i interface{}, err error) {
		// 创建grpc客户端
		cli := swarm.NewImageServerClient(conn)
		//客户端向grpc服务端发起请求
		return cli.Tag(context.Background(), &swarm.ReqImageTag{Source: source, Target: target})
	})
	if nil == err {
		if response, ok := resp.(*swarm.RespImageTag); ok {
			return response, nil
		}
		return nil, errors.New("image remove failed, can not tarns interface to response")
	}
	return nil, errors.Wrap(err, "image remove failed")
}
